package com.oracle.lingshangejia;


import android.content.Context;
import android.os.Build;
import android.os.StrictMode;
import android.support.annotation.RequiresApi;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;
import android.util.Log;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.oracle.lingshangejia.utils.MyToast;
import com.oracle.lingshangejia.utils.SpUtils;
import com.lws.bugly.Bugly;


import java.util.logging.Level;

import cn.jpush.android.api.JPushInterface;
import io.agora.AgoraAPIOnlySignal;
import io.agora.rtc.IRtcEngineEventHandler;
import io.agora.rtc.RtcEngine;
import okhttp3.OkHttpClient;


public class MyApp extends MultiDexApplication {
    private static Context context;

    private String TAG="MyApp";
    private AgoraAPIOnlySignal m_agoraAPI;
    private static MyApp mInstance;
    public RtcEngine mRtcEngine;
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)

    @Override
    public void onCreate() {

        super.onCreate();
        context = getApplicationContext();
        MyToast.context = context;

        //android 7.0系统解决拍照的问题
        StrictMode.VmPolicy.Builder builder1 = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder1.build());
        builder1.detectFileUriExposure();

        setupAgoraEngine();

        initOkGo();

        initOcr();

        Bugly.init(getApplicationContext());


        JPushInterface.init(this);



    }
    public MyApp() {
        mInstance = this;
    }
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(base);
    }
    public static MyApp the() {
        return mInstance;
    }

    /**
     * 初始化ocr
     */
    private void initOcr() {
        OCR.getInstance(MyApp.this).initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                // 调用成功，返回AccessToken对象
                String token = result.getAccessToken();
                SpUtils.put(MyApp.this,"ocrtoken",token);
            }
            @Override
            public void onError(OCRError error) {
                // 调用失败，返回OCRError子类SDKError对象
            }
        }, getApplicationContext(), "IOfn71lXjSrT9s2vgc7WShhj", "f6KYzIK9rbRYBDG8vkAjCVI0b24BVnS7");
    }


    private void initOkGo() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //log相关
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);        //log打印级别，决定了log显示的详细程度
        loggingInterceptor.setColorLevel(Level.INFO);                               //log颜色级别，决定了log在控制台显示的颜色
        builder.addInterceptor(loggingInterceptor);                                 //添加OkGo默认debug日志
        //第三方的开源库，使用通知显示当前请求的log，不过在做文件下载的时候，这个库好像有问题，对文件判断不准确
        // 详细说明看GitHub文档：https://github.com/jeasonlzy/
        OkGo.getInstance().init(this)                           //必须调用初始化
                .setOkHttpClient(builder.build())               //建议设置OkHttpClient，不设置会使用默认的
                .setCacheMode(CacheMode.NO_CACHE)               //全局统一缓存模式，默认不使用缓存，可以不传
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)   //全局统一缓存时间，默认永不过期，可以不传
                .setRetryCount(1);                            //全局统一超时重连次数，默认为三次，那么最差的情况会请求
    }
    public AgoraAPIOnlySignal getmAgoraAPI() {
        return m_agoraAPI;
    }

    private OnAgoraEngineInterface onAgoraEngineInterface;

    public RtcEngine getmRtcEngine() {
        return mRtcEngine;
    }
    public final IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() {
        @Override
        public void onFirstRemoteVideoDecoded(final int uid, int width, int height, int elapsed) {
            if (onAgoraEngineInterface != null) {
                onAgoraEngineInterface.onFirstRemoteVideoDecoded(uid, width, height, elapsed);
            }
        }

        @Override
        public void onUserOffline(int uid, int reason) {
            Log.i(TAG, "onUserOffline uid: " + uid + " reason:" + reason);
            if (onAgoraEngineInterface != null) {
                onAgoraEngineInterface.onUserOffline(uid, reason);
            }
        }

        @Override
        public void onUserMuteVideo(final int uid, final boolean muted) {
            //远端用户停止/恢复发送视频流回调。
            //提示有其他用户暂停/恢复了视频流的发送。
            if (onAgoraEngineInterface != null) {
                onAgoraEngineInterface.onUserMuteVideo(uid, muted);
            }
        }

        @Override
        public void onJoinChannelSuccess(String channel, int uid, int elapsed) {
            super.onJoinChannelSuccess(channel, uid, elapsed);
            // channel	频道名
            // uid	用户 ID 。如果 joinChannel 中指定了 uid，则此处返回该 ID；否则使用 Agora 服务器自动分配的 ID
            Log.i(TAG, "onJoinChannelSuccess channel:" + channel + " uid:" + uid);
            if (onAgoraEngineInterface != null) {
                onAgoraEngineInterface.onJoinChannelSuccess(channel, uid, elapsed);
            }
        }

    };
    public void setOnAgoraEngineInterface(OnAgoraEngineInterface onAgoraEngineInterface) {
        this.onAgoraEngineInterface = onAgoraEngineInterface;
    }
    public interface OnAgoraEngineInterface {
        void onFirstRemoteVideoDecoded(final int uid, int width, int height, int elapsed);

        void onUserOffline(int uid, int reason);

        void onUserMuteVideo(final int uid, final boolean muted);

        void onJoinChannelSuccess(String channel, int uid, int elapsed);
    }
    private void setupAgoraEngine() {
        String appID = getString(R.string.agora_app_id);
        try {
            m_agoraAPI = AgoraAPIOnlySignal.getInstance(this,appID);

            Log.i(TAG, "setupAgoraEngine mRtcEngine :" + mRtcEngine);
        } catch (Exception e) {
            Log.e(TAG, Log.getStackTraceString(e));
            throw new RuntimeException("NEED TO check rtc sdk init fatal error\n" + Log.getStackTraceString(e));
        }
    }
    public static Context getContext() {
        return context;
    }

    public static void logout(){
        if ( mInstance.m_agoraAPI != null){
            mInstance.m_agoraAPI.logout();
            mInstance.m_agoraAPI.destroy();
            // mInstance.m_agoraAPI = null;
        }
    }

}

